<template>
    <div class="box h100">
        <el-card class="dep-tree h100 ovy" v-show="!mode">
            <div class="top-action">
                <el-button type="text" href="" @click="addDep()">{{btnRootText}}</el-button>
                <el-button type="text" @click="backup" v-if="false">导出</el-button>
                <el-upload
                        style="margin-left: 10px;"
                        class="upload-demo"
                        ref="upload"
                        :action="importUrl"
                        :auto-upload="true"
                        :show-file-list="false"
                        :on-success="restore"
                        :before-upload="beforeRestore"
                >
                    <el-button slot="trigger" type="text" v-if="false">导入</el-button>
                </el-upload>
            </div>
            <el-tree
                    :data="tableData"
                    node-key="id"
                    :expand-on-click-node="false"
                    :props="{label: 'name'}"
                    :default-expanded-keys="show"
                    @node-click="d => showMeUsers(d.id)"
            >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                    <span class="action">
                        <slot name="action" :data="data"></slot>
                        <i class="el-icon-plus primary-color" :title="'添加' + singleName" @click="addDep(data)" v-if="allowChildren === true"></i>
                        <i class="el-icon-edit primary-color" :title="'编辑' + singleName" @click="editDep(data)"></i>
                        <i class="el-icon-delete danger-color" :title="'删除' + singleName" @click="delDep(data)"></i>
                    </span>
                </span>
            </el-tree>
        </el-card>
        <el-card class="h100 ovy" v-if="mode" style="flex: 1">
            <div class="pgh">
                <el-page-header @back="mode = ''" :content="mode == 'add' ? ('新建' + singleName) : ('编辑' + singleName)">
                </el-page-header>
            </div>
            <el-form :model="single" label-width="80px" style="" :rules="rules" ref="form">
                <el-form-item :label="singleName + '名'" prop="name" >
                    <el-input v-model="single.name" style="width: 400px;"></el-input>
                </el-form-item>
                <el-form-item label="上级部门" prop="pid" v-if="allowChildren === true">
                    <el-select v-model="single.pid">
                        <el-option label="顶级分类" :value="null"></el-option>
                        <el-option v-for="v in depList" :label="v.path" :value="v.id"></el-option>
                    </el-select>
<!--                    <el-input v-model="single.name"></el-input>-->
                </el-form-item>
                <el-form-item label="排序">
                    <el-input-number v-model="single.sort"/>
                </el-form-item>
<!--                @tag-->
                <el-form-item label="标签" v-if="false">
                    <ResourceTag ref="tag"  :setting="setting" :tag-key="tagKey" :data="single.tag_info || []"></ResourceTag>
                </el-form-item>
                <div style="text-align: center">
                    <el-button type="primary" icon="el-icon-check" @click="save(true)" :loading="saving">
                        保存关闭
                    </el-button>
                    <el-button type="primary" icon="el-icon-check" @click="save(false)" :loading="saving" v-if="mode == 'add'">
                        保存继续新建
                    </el-button>
                </div>
            </el-form>

        </el-card>
        <el-card class="set-person h100 ovy" v-show="!mode" v-loading="loading" ref="setPerson">
            <el-tabs>
                <el-tab-pane :label="`${v}(共${(data[i]||[]).length}人)`" v-for="(v,i) in types">
                    <UserPicker :search-user-url="searchUserUrl" :target="data[i]" @user-add="(r) => addUser(i,r)" @user-del="(r) => delUser(i,r)"/>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
    <!--    <el-tabs v-model="currentTab" class="box">-->
<!--        <el-tab-pane label="部门管理" name="first" class="dep">-->


<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="添加用户" name="addUser" v-if="currentTab == 'addUser'">-->
<!--            <UserPicker/>-->
<!--        </el-tab-pane>-->
<!--    </el-tabs>-->
</template>
<script>
    import $ from "jquery";
    import UserPicker from "../components/UserPicker";
    import ResourceTag from "../components/ResourceTag";
    import download from "../libs/download"

    export default {
        props:{
            //删除提示文字
            delMessage:"",
            //获取列表URL
            listUrl:"",
            //用户列表查询url
            searchUserUrl:"",
            //查询所属用户URL
            usersUrl:"",
            //添加用户URL
            addUserUrl:"",
            //删除用户URL
            delUserUrl:"",
            //保存URL
            saveUrl:"",
            //删除URL
            delUrl:"",
            //默认标签使用的字段
            tagKey:"",
            exportUrl:"",
            importUrl:"",
            btnRootText:"",
            allowChildren: false,
            //可添加的人员类型对照
            types:{
                type: Object,
                default:() => {
                    return {}
                }
            },
            //每一项的名字
            singleName:""
        },
        components: {
            UserPicker,
            ResourceTag
        },
        data() {
            return {
                mode:"",
                tableData: [],
                depList:[],
                show: [],
                users: [],
                data: {
                },
                single:{
                },
                loading: false,
                saving: false,

                rules:{
                    name: {required: true, message: '请输入'+this.singleName+'名', trigger: 'blur'},
                },
                oid: "",
                setting: {}
            }
        },
        methods: {
            load(expand = false) {
                $.when($.get(this.listUrl)/*, $.get("/api/v20/setting/get")*/).then((a,b) => {
                    // console.log(json.data,b)
                    //标签默认字段
                    // this.setting = b[0].data || {};

                    var json = a;
                    var walk = (path, deep, children) => {
                        children.forEach(e => {
                            this.depList.push(e);
                            e.deep = deep + 1;
                            e.path = "　".repeat(deep) + e.name;
                            walk(e.path, e.deep, e.children || []);
                        });
                    };
                    walk(null, 0, json.data||[]);

                    this.tableData = [];
                    this.$nextTick(_ => {
                        this.tableData = json.data || [];
                        if(expand){
                            this.tableData.length && (this.show = [this.tableData[0].id]);
                            if(this.$route.params.id == -1){
                                //展开第一行
                                this.show && this.showMeUsers(this.show[0]);
                            } else {
                                this.showMeUsers(this.$route.params.id);
                            }
                        }
                    });
                });
            },

            /**
             * 查看该部门用户
             */
            showMeUsers(id, e){
                if(e){
                    console.log(e)
                }
                this.loading = true;
                this.oid = id;
                $.get(this.usersUrl/*"/api/v20/dep/getUsers"*/, {id}, json => {
                    this.loading = false;
                    $(this.$refs.setPerson.$el).scrollTop(0);
                    this.data = json.data || {};
                }, "json") ;
            },
            /**
             * 删除单个用户
             */
            delUser(type, r){
                // console.log(arguments)
                // (this.data[type]||{}).splice(scope.$index, 1);
                $.get(this.delUserUrl /*"/api/v20/dep/delUser"*/, {type, uid: r.uid, oid: this.oid}, json => {});
            },
            addUser(type,r){
                console.log(arguments)
                $.get(this.addUserUrl /*"/api/v20/dep/addUser"*/, {type, uid: r.uid, oid: this.oid}, json => {});
                // this.currentTab = "addUser";
            },

            addDep(v = {}){
                this.single = {
                    pid: v.id || null,
                    sort: 0
                };
                this.mode = "add";
                this.$nextTick(_ => this.$refs.tag.clear())
            },
            editDep(v){
                // @tag
                // if(typeof v.tag_info === 'string'){
                //     v.tag_info = JSON.parse(v.tag_info);
                // }
                this.single = JSON.parse(JSON.stringify(v));
                this.mode = 'edit';
            },
            save(close){
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.saving = true;
                        //日掉children
                        var d = Object.assign({},this.single);
                        delete d.children;
                        //@tag
                        //补上tag_info
                        // d.tag_info = this.$refs.tag.tableData;
                        $.ajax({
                            url: this.saveUrl/*"/api/v20/dep/save"*/,
                            method: "post",
                            data: JSON.stringify(d),
                            dataType:"json",
                            headers:{
                                "content-type":"application/json"
                            },
                            success: (data) => {
                                if(!data.success){
                                    this.$notify.error({
                                        message: data.errMessage
                                    });
                                    return
                                }
                                this.load();
                                if(close){
                                    this.mode = "";
                                } else {
                                    this.addDep({id:d.pid});
                                    this.$notify.success({
                                        title:"提示",
                                        message: "保存成功，请继续新建"
                                    })
                                }
                            },
                            error(){
                            },
                            complete: () =>{
                                this.saving = false;
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            async delDep(v) {
                try {
                    await this.$confirm(this.delMessage, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'danger'
                    });
                    $.get(this.delUrl /*"/api/v20/dep/del"*/, {id: v.id}, (msg) => {
                        this.load();
                        this.$notify.success({
                            title: '提示',
                            message: '删除成功!'
                        });
                    }, "json");
                } catch (e) {
                }
            },
            backup(){
                download(this.exportUrl);
                this.$notify.info({
                    message:"正在导出，请稍后"
                })
            },
            beforeRestore(){
                this.$notify.info({
                    message:"开始导入，请稍后"
                });
            },
            restore(res){
                if(!res.success){
                    this.$notify.error({
                        message: res.errMessage//"导入成功"
                    });
                    return
                }
                console.log(res)
                this.load();
                this.$notify.success({
                    message: "导入成功"
                });
            },
            handleDrop(draggingNode, dropNode, dropType, ev) {
                console.log('tree drop: ', dropNode.label, dropType);
            },
        },

        mounted() {
            this.load(true)
        }
    }
</script>
<style scoped lang="less">
    .el-icon-plus{
        /*color: #409EFF;*/
        cursor: pointer;
        font-size: 16px;
    }
    .el-icon-edit{
        /*color: #E6A23C;*/
        cursor: pointer;
        font-size: 16px;
    }
    .el-icon-delete{
        /*color: #F56C6C;*/
        cursor: pointer;
        font-size: 16px;
    }
    .custom-tree-node{
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;

        .action i{
            margin-right: 10px;
        }
    }


   .box{
       display: flex;
       flex-direction: row;
       .dep-tree{
           flex: 1;
       }
       .set-person{
           flex: 2;
       }
   }

    /*.box{*/
    /*    width: 100%;*/
    /*    height: 100%;*/
    /*    overflow: hidden;*/
    /*    display: flex;*/
    /*    flex-direction: column;*/

    /*    .el-tabs__content{*/
    /*        flex: 1;*/

    /*        .dep {*/
    /*            height: 100%;*/
    /*            display: flex;*/
    /*            justify-content: space-between;*/

    /*            .dep-tree{*/
    /*                flex: 1;*/
    /*                overflow-y: auto;*/
    /*            }*/

    /*            .set-person{*/
    /*                flex: 2;*/
    /*                overflow-y: auto;*/
    /*                !*& .person-transfer{*!*/
    /*                !*    position: fixed;*!*/
    /*                !*    top: 0;*!*/
    /*                !*    left: 0;*!*/
    /*                !*}*!*/
    /*            }*/
    /*        }*/
    /*    }*/
    /*}*/
    .top-action{
        display: flex;
    }
</style>